<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
use Request;
use Hash;

class User extends Model
{
    /*用户注册函数API*/
    public  function signup()
    {
        $has_username_and_password = $this->has_username_and_password();
        if (!$has_username_and_password)
        {
            return ['status' => 0,'msg'=>'用户名和密码不可为空！'];
        }
        $username = $has_username_and_password[0];
        $password = $has_username_and_password[1];
        $user_exists = $this
            ->where('username',$username)
            ->exists();
        if ($user_exists){
            return ['status' => 0,'msg'=>'用户名已经存在！'];
        };
        $hashed_password = Hash::make($password);
        $user = $this;
        $user->password = $hashed_password;
        $user->username = $username;
        if ($user->save()){
            return ['status' => 1,'id'=>$user->id];
        }else{
            return ['status' => 0,'msg'=>'DB insert failed!'];
        }

    }
    /*用户登录API*/
    public function login(){
        /*检查用户名和密码是否存在*/
        $has_username_and_password = $this->has_username_and_password();
        if (!$has_username_and_password)
        {
            return ['status' => 0,'msg'=>'用户名和密码不可为空！'];
        }else{
            $username = $has_username_and_password[0];
            $password = $has_username_and_password[1];
        /*检查用户是否存在*/
            $user = $this->where('username',$username)->first();
            if(!$user)
            {
                return ['status' => 0,'msg'=>'用户不存在！'];
        /*检查密码是否正确*/
                $hashed_password = $user->password;
                if (!Hash::check($password,$hashed_password))
                {
                    return ['status' => 0,'msg'=>'密码不正确！'];
                }
            }
        }
        /*将用户信息写入session*/
        session()->put('username',$user->username);
        session()->put('user_id',$user->id);
//        dd(session()->all());
        return ['status' => 1,'id'=>$user->id];
    }

    /*退出登录函数*/
    public function loginout(){
        /*删除username和use_id*/
        session()->forget('username');
        session()->forget('user_id');
        /*返回首页*/
        return redirect('/');

    }


    /*判断用户名和密码是否存在*/
    public  function  has_username_and_password()
    {
        $username=rq('username');
        $password=rq('password');
        if ($username && $password)
        {
            return [$username,$password];
        }else{
            return false;
        }


    }
    /*检测用户是否登录函数*/
    public  function  is_logged_in()
    {
        /*如果session中存在user_id,就返回user_id,否则返回false*/
       return session('user_id') ?: false;
    }

}
